package com.bawei.module_motocircle.ui.post.adapter

import android.graphics.Color
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.bawei.lib_common.dp
import com.bawei.lib_common.utils.ToastUtils
import com.bawei.lib_image.GlideApp
import com.bawei.module_motocircle.R
import com.bawei.module_motocircle.databinding.LayoutItemPostListBinding
import com.bawei.module_motocircle.model.PostItem
import com.bumptech.glide.load.resource.bitmap.RoundedCorners

/**
 * @author yaotianxue
 * @description
 * @date 2025/6/2
 */
class PostViewHolder(
    val mBinding:LayoutItemPostListBinding,
    private val onItemClick: ((PostItem, Int) -> Unit)? = null,
    private val onUserClick: ((PostItem) -> Unit)? = null,
//    private val onImageClickWithThumbnail: ((Int, Int, List<Image>, List<Info>) -> Unit)? = null,
    private val onShareClick: ((PostItem) -> Unit)? = null,
    private val onCommentsClick: ((PostItem) -> Unit)? = null,
    private val onLikeClick: ((PostItem, Int) -> Unit)? = null,
    private val onMoreActionClick: ((PostItem, Int) -> Unit)? = null,
    private val onLikeViewClick: ((PostItem, Int, View) -> Unit)? = null,
    private val onCollectionViewClick: ((PostItem, Int, View) -> Unit)? = null,
    private val onFollowViewClick: ((PostItem, Int, View) -> Unit)? = null,
):RecyclerView.ViewHolder(mBinding.root) {
    private var postItem:PostItem? = null
    /**
     * 绑定数据和UI，databinding做不到的，需要自己写
     * 九宫格图片处理
     * 视频处理
     * 话题处理:富文本
     */
    fun initView(postItem:PostItem,position:Int){
        this.postItem = postItem

        mBinding.apply {
            lFollowState.isSelected = postItem.hasFollowed()
            //处理话题
            if (postItem.topics.isNullOrEmpty()){
                tvPostContent.text =  postItem.content
            }else{
                handleTopic(postItem)
            }
            //处理图片或视频
            handlePicOrVideo(postItem)
        }



    }

    private fun handlePicOrVideo(postItem: PostItem) {
        mBinding.apply {
            if (postItem.image?.size == 1 && postItem.image[0].contentType?.contains("video") == true) {
                lVideo.setOnClickListener {
                    clickItem()
                }
                //设置视频
                val video = postItem.image.firstOrNull() ?: return
                val videoHeight = video.imageHeight
                val videoWidth = video.imageWidth
                if (videoHeight > videoWidth) {
                    lVideo.setPortrait()
                    GlideApp.with(mBinding.root).load(video.url)
                        .override(343.dp,180.dp)
                        .transform(RoundedCorners(4.dp),)
                        .into(ivVideo)

                } else {
                    lVideo.setLandscape()
                    GlideApp.with(mBinding.root).load(video.url)
                        .override(311.dp,233.dp)
                        .transform(RoundedCorners(4.dp),)
                        .into(ivVideo)
                }
                ivPlay.visibility = View.VISIBLE
                //视频
                nineGridView.visibility = View.GONE
                lVideo.visibility = View.VISIBLE
            }else{
                nineGridView.setPicsList(postItem.image!!) //设置图片资源
                nineGridView.initView()
                nineGridView.visibility = View.VISIBLE
                lVideo.visibility = View.GONE
            }
        }

    }

    /**
     * 处理话题：富文本
     */
    private fun handleTopic(postItem: PostItem) {
        val content = postItem.content
        val spannableStringBuilder = SpannableStringBuilder(content)
        //保存话题的起始位置
        val topicIndexMap = mutableMapOf<String,MutableList<Int>>() //键:话题内容 值:话题开始和结束的位置
        //保存话题的id
        val topicIdMap = mutableMapOf<String,String>()//键:话题内容 值:话题id

        val topics = postItem.topics
        topics?.forEach{
            //话题前后加#
            val topicName = String.format("#%s#",it.topicName)
            //找的内容
            var temp = content

            while (true){
                val start = temp?.indexOf(topicName)
                if(start!! > -1){ //找到了
                    if(topicIndexMap[topicName] == null){
                        topicIndexMap[topicName] = mutableListOf()
                    }
                    topicIndexMap[topicName]?.add(start)
                    topicIndexMap[topicName]?.add(start+topicName.length)
                    topicIdMap[topicName] = it.topicId.toString()
                }else{ //没找到
                    break
                }
                //继续从后面开始找
                temp = temp?.substring(start+topicName.length)
            }
        }
        //今日份车溜子#日常溜车#   #日常溜车#   topicIndexMap:"#日常溜车#":[6,11]    topicIdMap:"#日常溜车#":"1643118469338963969"
        Log.d("handleTopic", "内容: $content")
        Log.d("handleTopic", "起始位置: $topicIndexMap")
        Log.d("handleTopic", "id: $topicIdMap")
        //富文本
        topicIndexMap.forEach{name,list ->
            spannableStringBuilder.setSpan(object : ClickableSpan(){
                override fun onClick(widget: View) {
                    ToastUtils.showLong(itemView.context,"点击了话题id ${topicIdMap[name]}")
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(itemView.context, R.color.topic)
                    ds.isUnderlineText = false
                }

            },list[0],list[1], SpannableStringBuilder.SPAN_EXCLUSIVE_INCLUSIVE)
        }
        mBinding.tvPostContent.apply {
            movementMethod = LinkMovementMethod.getInstance()
            highlightColor = Color.TRANSPARENT
            text = spannableStringBuilder

        }
    }

    fun clickItem(){
        onItemClick?.invoke(postItem!! ,this.absoluteAdapterPosition)
    }
    fun clickFollow(){
        onFollowViewClick?.invoke(postItem!! ,this.absoluteAdapterPosition,mBinding.lFollowState)
    }
    fun clickComment(){
        onCommentsClick?.invoke(postItem!!)
    }

    fun clickLike(){
        onLikeClick?.invoke(postItem!!,this.absoluteAdapterPosition)
        onLikeViewClick?.invoke(postItem!!, this.absoluteAdapterPosition,mBinding.placeholder)
    }
    fun clickCollection(){
        onCollectionViewClick?.invoke(postItem!!,this.absoluteAdapterPosition,mBinding.placeholderCollection)
    }
    fun clickMore(){
        onMoreActionClick?.invoke( postItem!!,this.absoluteAdapterPosition)
    }


}

fun View.setLandscape() {
    val l = layoutParams
    l.width = 343.dp
    l.height = 180.dp
    layoutParams = l
}

fun View.setPortrait() {
    val l = layoutParams
    l.width = 233.dp
    l.height = 311.dp
    layoutParams = l
}

